from flask import views, render_template, request, url_for, \
    jsonify, Blueprint
import json
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy.exc import SQLAlchemyError
from mysql_config import db
from models import User
from result_code import Code
from result import Result


user = Blueprint('user_control', __name__)


@jwt_required()
@user.route('/user/<uid>', methods=['GET', 'POST'])
def user_controller(uid):
    if request.method == 'GET':  # 用户查询
        # 返回值为对应模型类的类型(编写的用于表映射的类)
        res = User.query.filter(User.uid == uid).first()
        if res is None:
            resp = vars(Result(Code.GET_ERR.value, None, ''))
            return resp
        else:
            user_dic = vars(res)  # 将对象转换为字典
            # 因为每个查询得到的对象都会带一个名为_sa_instance_state的成员
            # _sa_instance_state的值的类型并不符合json类型的值
            # 所以要将_sa_instance_state的键值对去除
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, user_dic, 'select by id'))
            print(resp)
            return resp  # flask会自动将字典类型的数据转换为json数据响应到浏览器

    else:  # 用户修改
        pass


@user.route('/user/query', methods=['POST'])
def user_query():
    uid = request.json.get("uid")
    username = request.json.get("username")
    tel = request.json.get("tel")
    mail = request.json.get("mail")

    if uid != '':
        user1 = User.query.filter(User.uid == uid).first()
        if user1 is None:
            resp = vars(Result(Code.GET_ERR.value, None, '未查询到结果'))
            return resp
        else:
            user_dic = vars(user1)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], '用户列表'))
            return resp
    elif username != '':
        user2 = User.query.filter(User.username == username).first()
        if user2 is None:
            resp = vars(Result(Code.GET_ERR.value, None, '未查询到结果'))
            return resp
        else:
            user_dic = vars(user2)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], '用户列表'))
            return resp
    elif tel != '':
        user3 = User.query.filter(User.tel == tel).first()
        if user3 is None:
            resp = vars(Result(Code.GET_ERR.value, None, '未查询到结果'))
            return resp
        else:
            user_dic = vars(user3)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], '用户列表'))
            return resp
    else:
        user4 = User.query.filter(User.mail == mail).first()
        if user4 is None:
            resp = vars(Result(Code.GET_ERR.value, None, '未查询到结果'))
            return resp
        else:
            user_dic = vars(user4)
            del user_dic['_sa_instance_state']
            resp = vars(Result(Code.GET_ERR.value, [user_dic], '用户列表'))
            return resp


@user.route('/user/setadmin/<uid>', methods=['GET'])
def user_set_admin(uid):
    res_user = User.query.filter(User.uid == uid).first()
    if res_user is None:
        return {'msg': '操作失败'}
    try:
        res_user.actor = 1
        db.session.commit()
        return {'msg': '操作成功'}
    except SQLAlchemyError as e:
        db.session.rollback()
        return {'msg': '操作失败'}